﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WC3Game
{

    public static class Extensions
    {
        public static short ToShort(this byte[] data)
        {
            byte[] byteArray = new byte[] { (byte)data[0], (byte)data[1] };
            short int16 = 0;
            if (!BitConverter.IsLittleEndian)
                byteArray = byteArray.Reverse().ToArray();

            int16 = BitConverter.ToInt16(byteArray, 0);

            return int16;
        }

        public static T[] Range<T>(this T[] dataArray, int startIdx, int stopIdx)
        {
            List<T> list = new List<T>();

            if (stopIdx == -1)
                stopIdx = dataArray.Length;

            for (int i = startIdx; i < stopIdx; i++)
            {
                if (i >= dataArray.Length)
                    Console.WriteLine("Frame: {0}", Session.FrameCounter);

                try
                {
                    list.Add(dataArray[i]);
                }
                catch (IndexOutOfRangeException)
                {
                    // Might be waiting on more info.
                    return new T[] { };
                }
            }

            return list.ToArray();
        }

        public static String ExtractString(this byte[] dataArray, int startIdx)
        {
            List<byte> list = new List<byte>();

            int stopIdx = dataArray.Length;

            for (int x = startIdx; x < stopIdx; x++)
            {
                if (dataArray[x] == 0x00)
                {
                    stopIdx = -1;
                    break;
                }

                list.Add(dataArray[x]);
            }

            return list.ToArray().GetString();
        }

        public static T[] Range<T>(this T[] dataArray, int start)
        {
            return dataArray.Range<T>(start, -1);
        }

        public static String GetString(this byte[] byteArray)
        {
            if (byteArray.Length == 0 || byteArray[0] == 0x00)
                return String.Empty;

            return ASCIIEncoding.ASCII.GetString(byteArray);
        }

        public static String ToTimeFormat(this SharpPcap.Packets.Util.Timeval time)
        {
            TimeSpan t = TimeSpan.FromSeconds(time.Seconds);

            string gameTime = string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds,
                                    t.Milliseconds);

            return gameTime;
        }
    }

}
